﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ND.Tool;
using TableFieldInfo = ND.Tool.DB4CodeAuto.TableFieldInfo;
using TableInfo = ND.Tool.DB4CodeAuto.TableInfo;

namespace AutoCode.Win
{
    public class CodeAuto
    {
        /// <summary>
        /// 实体层代码自动化
        /// </summary>
        public void CreateModelCode(string p_str,bool iffugai,string namespacestr)
        {
            DB4CodeAuto dbc = new DB4CodeAuto();
            #region old code

            IList<TableInfo> list_table = dbc.TableListGet();

            for (int i = 0; i < list_table.Count; i++)
            {
                if (list_table[i].Name.IndexOf("201") > 0)
                    continue;
                IList<TableFieldInfo> list_field = dbc.TableFieldListGet(list_table[i].Name);

                TemplateEngine templateEngine = new TemplateEngine();

                templateEngine.SetFile("Tem", Config.AppDir + "/model.tpl");
                templateEngine.SetBlock("Tem", "FieldList1", "list1", "<!--\\s+BEGIN FieldList1\\s+-->([\\s\\S.]*)<!--\\s+END FieldList1\\s+-->");
                templateEngine.SetBlock("Tem", "FieldList2", "list2", "<!--\\s+BEGIN FieldList2\\s+-->([\\s\\S.]*)<!--\\s+END FieldList2\\s+-->");
                templateEngine.m_noMarkers = "comment";

                templateEngine.SetVal("t_name", list_table[i].Name, false);
                templateEngine.SetVal("t_note", list_table[i].Note, false);
                templateEngine.SetVal("t_object", list_table[i].Name, false);
                templateEngine.SetVal("t_namespace",namespacestr, false);

                if (list_table[i].Tables != "")
                {
                    string[] arr = list_table[i].Tables.Split(new char[] { ',' });
                    for (int j = 0; j < arr.Length - 1; j++)
                    {
                        var info = TableHelper.GetTable(arr[j].Replace(p_str, ""));
                        templateEngine.SetVal("t_object6", "[DataMember]", false);
                        templateEngine.SetVal("t_object5", info.OutTable, false);
                        if (info.TableFiled == "")
                            templateEngine.SetVal("t_object8", "", false);
                        else
                            templateEngine.SetVal("t_object8", "Of" + info.TableFiled, false);
                        templateEngine.Parse("list1", "FieldList1", true);
                    }
                }
                else
                {
                    templateEngine.SetVal("t_object8", "", false);
                    templateEngine.SetVal("t_object6", "", false);
                    templateEngine.SetVal("t_object5", "", false);
                    templateEngine.Parse("list1", "FieldList1", true);
                }

                foreach (TableFieldInfo f in list_field)
                {
                    templateEngine.SetVal("f_name", dbc.FilterFieldName(FilterTableFiledName(f.ColName)), false);
                    templateEngine.SetVal("f_type", ChangeToJavaTypeForModel((f.ColType == "short" || f.ColType == "int" || f.ColType == "decimal" || f.ColType == "double" || f.ColType == "bool") ? (f.IsNullAble == "1" ? f.ColType + "?" : f.ColType) : f.ColType), false);
                    templateEngine.SetVal("f_note", f.PropValue, false);
                    templateEngine.Parse("list2", "FieldList2", true);
                }
                templateEngine.Parse("out", "Tem", false);

                string cont = templateEngine.PutOutPageCode("out");
                //if (cont.Contains("public Info Info { get; set; }"))
                //{
                //    cont = cont.Replace("public Info Info { get; set; }", "");
                //}
                string file = Config.Dir + "/Model/auto/" + list_table[i].Name + "_model.cs";
                if (Config.Tpl.ToLower() == "java")
                    file = Config.Dir + "/model/auto/" + list_table[i].Name + "_model.java";

                if (!System.IO.File.Exists(file) || iffugai)
                    Common.CreateFile(file, cont);

            }
            #endregion
        }

        /// <summary>
        /// 实体层代码自动化
        /// </summary>
        public void CreateDalCode(bool iffugai, string namespacestr)
        {
            DB4CodeAuto dbc = new DB4CodeAuto();
            #region old code

            IList<TableInfo> list_table = dbc.TableListGet();

            for (int i = 0; i < list_table.Count; i++)
            {
                if (list_table[i].Name.IndexOf("201") > 0)
                    continue;
                IList<TableFieldInfo> list_field = dbc.TableFieldListGet(list_table[i].Name);

                //默认第一个字段为主键
                string mainkeytype = list_field[0].ColType;
                string mainkeyname = list_field[0].ColName;

                TemplateEngine templateEngine = new TemplateEngine();

                templateEngine.SetFile("Tem", Config.AppDir + "/dal.tpl");
                for (int j = 1; j <= 6; j++)
                {
                    templateEngine.SetBlock("Tem", "FieldList"+j, "list"+j, "<!--\\s+BEGIN FieldList" + j + "\\s+-->([\\s\\S.]*)<!--\\s+END FieldList" + j + "\\s+-->");
                }

                templateEngine.m_noMarkers = "comment";

                templateEngine.SetVal("t_name", list_table[i].Name, false);
                templateEngine.SetVal("t_note", list_table[i].Note, false);
                templateEngine.SetVal("t_object", list_table[i].Name, false);
                templateEngine.SetVal("t_namespace", namespacestr, false);
                templateEngine.SetVal("t_mainkeyname", mainkeyname, false);
                templateEngine.SetVal("t_mainkeytype", mainkeytype, false);

                string ID = "";
                foreach (TableFieldInfo f in list_field)
                {
                    if (f.ColName.ToLower() == mainkeyname)
                    {
                        ID = f.ColName;
                        break;
                    }
                }
                templateEngine.SetVal("t_idFiled", FilterTableFiledName(ID), false);

                for (int j = 1; j <= 5; j++)
                { 
                    foreach (TableFieldInfo f in list_field)
                    {
                        if (f.ColName.ToLower() == mainkeyname)
                            continue;
                        templateEngine.SetVal("f_name" + j, f.ColName, false);
                        templateEngine.SetVal("f_name_model" + j, dbc.FilterFieldName(FilterTableFiledName(f.ColName)), false);
                        templateEngine.SetVal("f_note" + j, f.PropValue, false);
                        templateEngine.Parse("list" + j, "FieldList" + j, true);

                    }
                    templateEngine.RemoveSuffix("list"+j, ",");
                }

                foreach (TableFieldInfo f in list_field)
                {
                    templateEngine.SetVal("f_name6", f.ColName, false);
                    templateEngine.SetVal("f_name_model6", dbc.FilterFieldName(FilterTableFiledName(f.ColName)), false);
                    templateEngine.SetVal("f_note6", f.PropValue, false);
                    var coltype = f.ColType;
                    if (Config.Tpl.ToLower() == "java")
                    {
                        coltype = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(coltype);
                    }
                    templateEngine.SetVal("f_type6", ChangeToJavaTypeForDal(coltype), false);
                    templateEngine.Parse("list6", "FieldList6", true);

                }
                templateEngine.RemoveSuffix("list6", ",");
               
               
                templateEngine.Parse("out", "Tem", false);

                string cont = templateEngine.PutOutPageCode("out");
                //if (cont.Contains("public Info Info { get; set; }"))
                //{
                //    cont = cont.Replace("public Info Info { get; set; }", "");
                //}
                string file = Config.Dir + "/Dal/auto/" + list_table[i].Name + "_dal.cs";
                if (Config.Tpl.ToLower() == "java")
                    file = Config.Dir + "/dal/auto/" + list_table[i].Name + "_base_dal.java";

                if (!System.IO.File.Exists(file) || iffugai)
                    Common.CreateFile(file, cont);

            }
            #endregion
        }
            /// <summary>
        /// 格式化表名
        /// </summary>
        /// <param name="p_tableName"></param>
        /// <returns></returns>
        private string FormatTableName(string p_tableName, string p_str1, bool p_is)
        {
            if (p_str1 != "")
                p_tableName = p_tableName.Replace(p_str1, "");

            string[] arr = p_tableName.Split(new char[] { '_' });

            string str = "";
            for (int i = 0; i < arr.Length; i++)
            {
                if (p_is)
                    str += arr[i].Substring(0, 1).ToLower() + arr[i].Substring(1);
                else
                    str += arr[i];
            }

            return str;
        }

        private string FilterTableFiledName(string p_tablefiledName)
        {
            return p_tablefiledName.Replace("f_","");
        }

        private string ChangeToJavaTypeForModel(string type)
        {
            if (Config.Tpl.ToLower() == "java")
            {
                string ltype = type.ToLower();
                if (ltype == "string")
                    return "String";
                if (ltype == "datetime")
                    return "java.util.Date";
            }
                return type;
        }

        private string ChangeToJavaTypeForDal(string type)
        {
            if (Config.Tpl.ToLower() == "java")
            {
                string ltype = type.ToLower();
                if (ltype == "string")
                    return "Str";
                if (ltype == "datetime")
                    return "DateTime";
                if (ltype == "long")
                    return "Int64";
            }
            return type;
        }

    }
}
